//
//  SHLoginViewController.swift
//  ServiceHelper
//
//  Created by Stan Wu on 15/4/9.
//  Copyright (c) 2015 Stan Wu. All rights reserved.
//

import UIKit

protocol SHLoginDelegate{
    func accountLoginned() -> Void
}

class SHLoginViewController: UIViewController {
    var tfUsername,tfPassword: UITextField!
    var delegate: SHLoginDelegate?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let imgvBG = UIImageView(image: UIImage(named: "LoginBG"))
        self.view.addSubview(imgvBG);
        
        let imgvIcon = UIImageView(image: UIImage(named: "logo"))  //HaimaIcon
        imgvIcon.center = CGPointMake(512, 35+imgvIcon.frame.size.height/2)
        self.view.addSubview(imgvIcon)
        
        tfUsername = UITextField(frame: CGRectMake(287, 230, 1024-287*2, 50));
        tfUsername.clipsToBounds = true
        tfUsername.layer.cornerRadius = 4
        tfUsername.layer.borderWidth = 0.5
        tfUsername.backgroundColor = UIColor(white: 0.97, alpha: 1)
        tfUsername.layer.borderColor = UIColor(red: 0.58, green: 0.62, blue: 0.67, alpha: 1).CGColor
        tfUsername.layer.sublayerTransform = CATransform3DMakeTranslation(120, 0, 0)
        self.view.addSubview(tfUsername)
        tfUsername.becomeFirstResponder()
        
        var frame = self.view.convertRect(CGRectMake(11, 0, 106, tfUsername.frame.size.height), fromView: tfUsername)
        var lbl: UILabel = UILabel.create(frame, font: UIFont.systemFontOfSize(21), textColor: UIColor.blackColor())
        lbl.text = "登录账号"
        self.view.addSubview(lbl)

        tfPassword = UITextField(frame: CGRectMake(287, 280, 1024-287*2, 50));
        tfPassword.clipsToBounds = true
        tfPassword.layer.cornerRadius = 4
        tfPassword.layer.borderWidth = 0.5
        tfPassword.backgroundColor = UIColor(white: 0.97, alpha: 1)
        tfPassword.layer.borderColor = UIColor(red: 0.58, green: 0.62, blue: 0.67, alpha: 1).CGColor
        tfPassword.layer.sublayerTransform = CATransform3DMakeTranslation(120, 0, 0)
        tfPassword.secureTextEntry = true
        self.view.addSubview(tfPassword)
        
        
        frame = self.view.convertRect(CGRectMake(11, 0, 106, tfPassword.frame.size.height), fromView: tfPassword)
        lbl = UILabel.create(frame, font: UIFont.systemFontOfSize(21), textColor: UIColor.blackColor())
        lbl.text = "登录密码"
        self.view.addSubview(lbl)
        
        let btn: UIButton = UIButton(frame: CGRectMake(287, 345, 1024-287*2, 45))
        btn.clipsToBounds = true
        btn.layer.cornerRadius = 4
        btn.layer.borderWidth = 1
        btn.layer.borderColor = UIColor(white: 1, alpha: 0.5).CGColor
        //TODO: 今天就先写到这吧睡觉 明天继续
        if #available(iOS 9.0, *) {
            
            //高于 iOS 9.0
            
        } else {
            
            //低于 iOS 9.0
            
        }
        btn.setBackgroundImage(UIImage(named: "button_bule"), forState: UIControlState.Normal)
        btn.titleLabel?.font = UIFont.systemFontOfSize(23)
        btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        btn.setTitle("登录", forState: .Normal)
        btn.addTarget(self, action: #selector(SHLoginViewController.loginClicked), forControlEvents: .TouchUpInside)
        self.view.addSubview(btn)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        let touch = (touches as NSSet).anyObject()
        if (tfUsername.isFirstResponder() || tfPassword.isFirstResponder()) && (touch?.view != tfPassword || touch?.view != tfUsername){
            tfUsername.resignFirstResponder()
            tfPassword.resignFirstResponder()
        }
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
    
    func loginClicked(){
        let username: String = tfUsername.text!
        let password: String = tfPassword.text!
//        username = "DT02-001"       
//        password = "DT02-123456"
        
//        username = "D07-001"
//        password = "D07-1234567"
        
//        username = "factory1"
//        password = "1"
        
//        username = "B121-001"
//        password = "888888"

//        username = "b51-001"
//        password = "123456"
        
        //D07-001   -  123456
        

        if !username.isEmpty && !password.isEmpty{
            let param = ["username":username,"password":password]
            NSThread.detachNewThreadSelector(#selector(SHLoginViewController.login(_:)), toTarget: self, withObject: param)
        }
    }
    
    func login(accountInfo: NSDictionary){
        let dict = SHDataProvider.login(accountInfo)
        
        let code = dict?.objectForKey("code")?.integerValue
        
        
        SWUtils.RunOnMainThread { () -> Void in
            if let result = code{
                if  result==200{
                    NSUserDefaults.standardUserDefaults().setObject(dict?.objectForKey("data"), forKey: "UserInfo")
                    NSUserDefaults.standardUserDefaults().synchronize()
                    self.delegate?.accountLoginned()
                }else{
                    let message = dict!.objectForKey("message") as! String!
                    UIAlertView.show(nil, message: message, cancelButton: nil)
                }
            }
            else{
                UIAlertView.show(nil, message: "网络异常，请稍候再试", cancelButton: nil)
            }
        }
        
    }

}
